using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace LetLord.Models
{
    public class TenantRepository : ITenantRepository
    {
        LetLordContext context = new LetLordContext();

        public IQueryable<Tenant> All
        {
            get { return context.UserProfile.OfType<Tenant>(); }
        }

        public IQueryable<Tenant> AllIncluding(params Expression<Func<Tenant, object>>[] includeProperties)
        {
            IQueryable<Tenant> query = context.UserProfile.OfType<Tenant>();
            foreach (var includeProperty in includeProperties)
            {
                query = query.Include(includeProperty);
            }
            return query;
        }

        public Tenant Find(int id)
        {
            return context.UserProfile.OfType<Tenant>().SingleOrDefault(t => t.UserId == id);
        }

        public Tenant GetLoggedInTenant()
        {
            return context.UserProfile.OfType<Tenant>().First(t => t.UserName == System.Web.HttpContext.Current.User.Identity.Name);
        }

        public void InsertOrUpdate(Tenant tenant)
        {
            if (tenant.UserId == default(int))
            {
                // New entity
                context.Set<Tenant>().Add(tenant);
            }
            else
            {
                // Existing entity
                context.Entry(tenant).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var tenant = context.UserProfile.OfType<Tenant>().SingleOrDefault(t => t.UserId == id);
            context.Set<Tenant>().Remove(tenant);
        }

        public byte[] GetReference(int id)
        {
            ReferencePhoto rp = context.Image.OfType<ReferencePhoto>().SingleOrDefault(i => i.ImageId == id);
            byte[] image = rp.File;
            return image;
        }

        public void Save()
        {
            context.SaveChanges();
        }

        public void Dispose()
        {
            context.Dispose();
        }
    }

    public interface ITenantRepository : IDisposable
    {
        IQueryable<Tenant> All { get; }
        IQueryable<Tenant> AllIncluding(params Expression<Func<Tenant, object>>[] includeProperties);
        Tenant Find(int id);
        Tenant GetLoggedInTenant();
        byte[] GetReference(int id);
        void InsertOrUpdate(Tenant tenant);
        void Delete(int id);
        void Save();
    }
}